package com.yifeng.repo.base.encryption;

import com.baomidou.mybatisplus.core.toolkit.AES;
import com.gomcarter.frameworks.base.common.AssertUtils;
import com.yifeng.repo.base.encryption.conf.NacosConfManager;
import com.yifeng.repo.base.utils.common.DesensitizedUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * Created by daibing on 2023/9/14.
 */
@Slf4j
public class DataGuarder {
    private static final NacosConfManager nacosConfManager = new NacosConfManager();

    public static String encrypt(String plaintext) {
        List<String> aesKeys = nacosConfManager.listAesKey();
        AssertUtils.notEmpty(aesKeys, "获取AES密钥为空！");
        return AES.encrypt(plaintext, aesKeys.get(0));
    }

    public static String decrypt(String ciphertext) {
        List<String> aesKeys = nacosConfManager.listAesKey();
        AssertUtils.notEmpty(aesKeys, "获取AES密钥为空！");
        for (String aesKey : aesKeys) {
            try {
                return AES.decrypt(ciphertext, aesKey);
            } catch (Exception e) {
                log.warn("AES解密失败：ciphertext={}, aesKey={}", ciphertext, DesensitizedUtil.desensitized(aesKey, DesensitizedUtil.DesensitizedType.FIRST_MASK));
            }
        }
        return null;
    }
}
